package services

import (
	"os"

	"gopkg.in/gomail.v2"
	"gopkg.in/yaml.v2"
)

// Config 配置文件结构体
type Config struct {
	Mail struct {
		SMTP     string `yaml:"smtp"`
		SMTPPort int    `yaml:"smtp-port"`
		User     string `yaml:"user"`
		Password string `yaml:"password"`
	} `yaml:"mail"`
}

// ReadConfig 读取配置文件
func ReadConfig(path string) (*Config, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}
	var config Config
	err = yaml.Unmarshal(data, &config)
	if err != nil {
		return nil, err
	}
	return &config, nil
}

// SendVerificationCode 发送验证码
func SendVerificationCode(email, code string) error {
	// 读取配置文件，获取邮箱配置，然后发送邮件
	config, err := ReadConfig("config/config.yaml")
	if err != nil {
		return err
	}

	m := gomail.NewMessage()
	m.SetHeader("From", config.Mail.User)
	m.SetHeader("To", email)
	m.SetHeader("Subject", "验证邮箱地址")
	m.SetBody("text/html", "你的邮箱验证码是: "+code+"\n\n请在120秒内完成验证")

	d := gomail.NewDialer(config.Mail.SMTP, config.Mail.SMTPPort, config.Mail.User, config.Mail.Password)
	return d.DialAndSend(m)
}
